import {
  domStrTpl,
  initStyleStr,
  innerDomStr
} from "../consts";

function setStyle() {
  let domSty = document.getElementById("weditorStyle");
  // 已经设置了style
  if(domSty && domSty.nodeName === "STYLE") return;
  loadStyleString(initStyleStr);
}

/**
 * 动态加载style
 * @param css 样式字符串
 */
function loadStyleString(css){
  var style = document.createElement("style");
  style.type = "text/css";
  style.id = "weditorStyle";
  try{
    style.appendChild(document.createTextNode(css));
  } catch (ex){
    style.styleSheet.cssText = css;
  }
  var head = document.getElementsByTagName("head")[0];
  head.appendChild(style);
}

/**
 * 根据不同的类型，生成最终需要插入DOM中的字符串
 * @param config 数据
 * @param type 类型
 */
function getInnerStr(config, type) {
  var rawStr = domStrTpl.replace(/element_placeholder/, innerDomStr[type + "Default"] || innerDomStr["stdIframeDefault"]);
  switch (type) {
    case "video":
      // 特指腾讯视频，本质是个iframe
      return format(rawStr, config.name, config.ifrSrc.replace("http:", ""));
    case "nativevideo":
      return format(rawStr, config.name, config.poster, config.src);
    case "nativeaudio":
      return format(rawStr, config.name, config.src);
    case "ZJflash":
      return format(rawStr, config.name, config.src);
    default:
      return format(rawStr, config.name, config.ifrSrc.replace("http:", ""));
  }
}

/**
 * 格式化字符串，{{}}替换
 * @return {*}
 */
function format() {
  if(arguments.length === 0) return "";
  var args = Array.prototype.slice.call(arguments, 0);
  var raw = args[0];
  args.shift();
  return raw.replace(/{{(\d)}}/g, function (all, child) {
    return args[child];
  })
}

/**
 * AES加密替换符号
 * + %2B
 * = %3D
 * / %2F
 * @param str
 * @param flag true 替换为安全的， false替换为原来的
 */
function cryptoEscape(str, flag) {
  if(flag === true){
    return str.replace(/\+/g, "_a1A_").replace(/=/g, "_b2B_").replace(/\//g, "_c3C_");
  }else{
    return str.replace(/_a1A_/g, "+").replace(/_b2B_/g, "=").replace(/_c3C_/g, "/");
  }
}
export {
  setStyle,
  getInnerStr,
  cryptoEscape
}
